using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Configuration;
using Db4objects.Db4o;
using Db4objects.Db4o.Messaging;

namespace Db4o.Framework.Server
{
    public sealed class Db4oServer : IMessageRecipient
    {
        protected static log4net.ILog logger = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

        #region Full lazy singleton pattern Db4oServer

        Db4oServer()
        {
        }

        public static Db4oServer Instance
        {
            get
            {
                return Nested.instance;
            }
        }

        class Nested
        {
            // Explicit static constructor to tell C# compiler
            // not to mark type as beforefieldinit
            static Nested()
            {
            }

            internal static readonly Db4oServer instance = new Db4oServer();
        }

        #endregion

        /// <summary>
        /// setting the value to true denotes that the server should be closed
        /// </summary>
        private bool stop = false;
        /// <summary>
        /// 
        /// </summary>
        private bool status = false;
        /// <summary>
        /// 
        /// </summary>
        public bool Status
        {
            get { return status; }
            set { status = value; }
        }


        /// <summary>
        /// opens the IObjectServer, and waits forever until Close() is called
        /// or a StopServer message is being received.
        /// </summary>
        public void RunServer()
        {
            lock (this)
            {

                IObjectServer db4oServer = Db4oFactory.OpenServer(
                    Properties.Settings.Default["FILE"].ToString(), 
                    Int32.Parse(Properties.Settings.Default["PORT"].ToString())
                    );
                db4oServer.GrantAccess(
                    Properties.Settings.Default["USER"].ToString(), 
                    Properties.Settings.Default["PASS"].ToString()
                    );

                // Using the messaging functionality to redirect all
                // messages to this.processMessage
                db4oServer.Ext().Configure().SetMessageRecipient(this);
                try
                {
                    if (!stop)
                    {
                        Status = true;
                        // wait forever for Notify() from Close()
                        Monitor.Wait(this);
                    }
                }
                catch (Exception e)
                {
                    Status = false;
                    logger.Fatal(e.ToString());
                }
                db4oServer.Close();
            }
        }
        public void CloseServer()
        {
            IObjectContainer IObjectContainer = null;
            try
            {
                // connect to the server
                IObjectContainer = Db4oFactory.OpenClient(
                    Properties.Settings.Default["HOST"].ToString(),
                    Int32.Parse(Properties.Settings.Default["PORT"].ToString()),
                    Properties.Settings.Default["USER"].ToString(),
                    Properties.Settings.Default["PASS"].ToString()
                    );
           
            }
            catch (Exception e)
            {
                logger.Fatal(e.ToString());
            }

            if (IObjectContainer != null)
            {
                // get the messageSender for the IObjectContainer
                IMessageSender messageSender = IObjectContainer.Ext().Configure().GetMessageSender();

                // send an instance of a StopServer object
                messageSender.Send(new Db4oServer());

                // close the IObjectContainer
                IObjectContainer.Close();
            }
        }

        /// <summary>
        /// messaging callback
        /// see com.db4o.messaging.MessageRecipient#ProcessMessage()
        /// </summary>
        public void ProcessMessage(IObjectContainer con, object message)
        {
            if (message is Db4oServer)
            {
                Close();
            }
        }

        /// <summary>
        /// closes this server.
        /// </summary>
        public void Close()
        {
            lock (this)
            {
                Status = false;
                stop = true;
                Monitor.PulseAll(this);
            }
        }

    }

}
